package org.example.springboot.interceptor;

import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.annotation.After;
import org.aspectj.lang.annotation.Aspect;
import org.example.springboot.utils.JwtUtils;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

@Component
@Aspect
@Slf4j
public class AopAlternativeInterceptor {
  @Value("${user.allowed-header}")
  private String CUSTOM_HEADER_NAME;

  @After("execution(* org.example.springboot.controller.*.*(..))")
  public void after() throws Throwable {
    HttpServletResponse response = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getResponse();
    HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest();

    assert response != null;

    addUserTokenToHeaders(request, response);
  }

  private void addUserTokenToHeaders(HttpServletRequest request, HttpServletResponse response) {
    if (request.getRequestURI().contains("/login")) {
      log.info("Redirecting to login page, setting token to response header {}", CUSTOM_HEADER_NAME);
      response.setHeader(CUSTOM_HEADER_NAME, JwtUtils.generateToken());  // 这里可以获取到 response.getHeader("Authorization")
    } else if (request.getRequestURI().contains("/logout")) {
      response.setHeader(CUSTOM_HEADER_NAME, null);
    } else {
      String token = request.getHeader(CUSTOM_HEADER_NAME);
      if (JwtUtils.validateToken(token)) {
        // Ensure always validated
        response.setHeader(CUSTOM_HEADER_NAME, JwtUtils.generateToken());
      }
      // tempora
      response.setHeader(CUSTOM_HEADER_NAME, JwtUtils.generateToken());
    }
  }


}
